package com.vader.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @author kaivader
 */
public class ChatServer {

    private Selector selector;

    private ServerSocketChannel listenChannel;

    private static final int PORT = 7777;

    public ChatServer() {
        try {
            selector = Selector.open();
            listenChannel = ServerSocketChannel.open();
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            listenChannel.configureBlocking(false);
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.getMessage();
        }
    }

    public void listen() {
        try {
            while (true) {
                int select = selector.select(2000);
                if (select > 0) {
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        if (selectionKey.isAcceptable()) {
                            SocketChannel socketChannel = listenChannel.accept();
                            socketChannel.configureBlocking(false);
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + "用户已连接");
                        }

                        if (selectionKey.isReadable()) {
                            readData(selectionKey);
                        }

                        iterator.remove();
                    }
                } else {
                    System.out.println("尚未有连接发生···");
                }
            }
        } catch (Exception e) {
            e.getMessage();
        }
    }

    public void readData(SelectionKey selectionKey) {
        SocketChannel channel = null;
        try {
            channel = (SocketChannel) selectionKey.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int read = channel.read(buffer);
            if (read > 0) {
                String msg = new String(buffer.array());
                System.out.println("from client" + msg);
                sendInfoToOther(msg, channel);
            }
        } catch (Exception exception) {
            try {
                if (channel != null) {
                    System.out.println(channel.getRemoteAddress() + "lost link");
                }
            } catch (IOException e) {
                e.getMessage();
            } finally {
                selectionKey.cancel();
                try {
                    if (channel != null) {
                        channel.close();
                    }
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
    }

    private void sendInfoToOther(String msg, SocketChannel source) throws IOException {
        System.out.println("send info to others");

        Set<SelectionKey> selectionKeys = selector.selectedKeys();
        for (SelectionKey selectionKey : selectionKeys) {
            SocketChannel channel = (SocketChannel) selectionKey.channel();
            channel.configureBlocking(false);
            if (channel != source) {
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                try {
                    channel.write(byteBuffer);
                } catch (IOException e) {
                    e.getMessage();
                }
            }
        }
    }

    public static void main(String[] args) {

        ChatServer chatServer = new ChatServer();
        chatServer.listen();
    }

}
